package com.lovvyang.servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @author lovvyang
 * @date 2020/6/10-23:06
 */
/*
 * @PackageName:com.lovvyang.servlet
 * @ClassName:DownLoadServlet
 * @Description
 * @author lovvyang
 * @date 2020/6/10/23:06
 **/
@WebServlet("/downLoadServlet")
public class DownLoadServlet  extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String filename = req.getParameter("filename");
        ServletContext servletContext = this.getServletContext();
        String realPath = servletContext.getRealPath("/img/" + filename);
        FileInputStream fileInputStream =new FileInputStream(realPath);
        String mimeType = servletContext.getMimeType(filename);
        resp.setHeader("content-type",mimeType);
        resp.setHeader("content-disposition","attachment;filename="+filename);
        ServletOutputStream outputStream = resp.getOutputStream();
        byte []arr =new byte[1024*8];
        int len =0;
        while ((len=fileInputStream.read(arr))!=-1){
            outputStream.write(arr,0,len);
        }
        fileInputStream.close();


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}
